import type { CSSProperties, FunctionalComponent } from 'vue'
import type { BodyCellProps } from '../types'

import { inject, renderSlot } from 'vue'
import clsx from 'clsx'
import { omit } from 'lodash-es'
import { TABLE_SLOT_KEY } from '../context'
import { DEFAULT_CELL_ALIGNMENT } from '../../grid/constants'

const BodyCellRenderer: FunctionalComponent<BodyCellProps> = (props) => {
  const slots = inject(TABLE_SLOT_KEY)
  const {
    record,
    column,
    columnIndex,
    rowIndex,
    className,
    style,
    key,
    clickHandler,
    dblclickHandler
  } = props
  const value = record[column.field]

  /**
   * 处理column.customCell
   */
  const customCell =
    typeof column.customCell === 'function'
      ? column.customCell({ value, record, rowIndex, column, columnIndex })
      : {}
  /**
   * 处理column.formatter
   */
  const cellValue =
    typeof column.formatter === 'function'
      ? column.formatter({ value, record, rowIndex, column, columnIndex })
      : value
  /**
   * 处理class
   * 注意column.customCell中返回的class在这里处理
   */
  const cellClass = clsx('virtualized-grid-cell', className, column.cellClassName, customCell.class)
  /**
   * 处理style
   */
  const cellStyle: CSSProperties = {
    textAlign: column.align || DEFAULT_CELL_ALIGNMENT,
    ...style
  }

  return (
    <div
      role="cell"
      aria-colindex={columnIndex}
      aria-rowindex={rowIndex}
      key={key}
      class={cellClass}
      style={cellStyle}
      {...omit(customCell, ['class', 'style'])}
      onClick={() => clickHandler({ value, record, column, rowIndex, columnIndex })}
      onDblclick={() => dblclickHandler({ value, record, column, rowIndex, columnIndex })}
    >
      {renderSlot(slots, 'bodyCell', { value, record, column, rowIndex, columnIndex }, () => {
        return column.cellRender
          ? [column.cellRender({ value, record, column, rowIndex, columnIndex })]
          : [<span>{cellValue}</span>]
      })}
    </div>
  )
}

BodyCellRenderer.displayName = 'BodyCellRenderer'

export default BodyCellRenderer
